let fs = require('fs');
let chalk = require('chalk');
let xlsx = require('node-xlsx');
let fsExtra = require('fs-extra');
let walkSync = require('walk-sync');

const outPathTxt = './tableData';
const outPahtTs =  './tableType';

function writeTypeFileOfTxt(_listData) {
  //按照表格中的第二行为基准计算
  let flagArray = _listData.data[1]; //第二行

  let outStr = '';
  let singleData = [];
  let nameStr = _listData.name; //文件名称
  let tempData = _listData.data; //文件内容

  let count = 0;
  for (let values of tempData) {
    singleData.length = 0;
    flagArray.forEach((value, index) => {
      if (value) {
        singleData.push(values[index]);
      }
    });
    count ++;
    if (count >= tempData.length) {
      outStr += singleData.join('`')
    }
    else {
      outStr += singleData.join('`') + '\r\n';
    }
  }

  //写入文件
  let writeStream = fs.createWriteStream(outPathTxt + '/' + nameStr + '.txt', { encoding: 'utf8' });
  writeStream.write(outStr);
  writeStream.end();

  writeStream.on('finish', function () {
    console.count('fileCount')
  });
}

function writeTypeFileOfTs(_listData) {
  let descArray = _listData.data[0]; //第一行
  let flagArray = _listData.data[1]; //第二行
  let typeArray = _listData.data[2]; //第三行

  let nameStr = _listData.name; //文件名称
  let outStr = '';
  let outStr1 = `export default class ${nameStr + 'Data'} {` + '\r\n';
  let outStr2 = '}';
  flagArray.forEach((value, index) => {
    if (value) {
      outStr += '\t' + '/// <summary>' + '\r\n\t' + '/// ' + descArray[index] + '\r\n\t' + '/// <summary>' + '\r\n\t' + flagArray[index] + ': ' + typeArray[index] + ';' + '\r\n';
    }
  })

  let writeStream = fs.createWriteStream(outPahtTs + '/' + nameStr + 'Data.ts', { encoding: 'utf8' });
  writeStream.write(outStr1 + outStr + outStr2);
  writeStream.end();
}

function setFileToDirectory(_listDatas) {
  for (let i = 0, j = _listDatas.length; i < j; i++) {
    //写入txt
    writeTypeFileOfTxt(_listDatas[i]);
    //写入ts
    writeTypeFileOfTs(_listDatas[i]);
  }
}

function repeatCheck(listDatas) {
  let tempArr = [];
  listDatas.forEach((value, index) => {
    if (tempArr.indexOf(value.name) != -1) {
      console.log(chalk.red(value.name + '名称重复！'))
    }
    else {
      tempArr.push(value.name);
    }
  })
}


let listDatas = [];
let sourcePath = process.argv[2];
if (sourcePath) {
  //获取表格路径
  let tablePaths = walkSync(sourcePath, { globs: ['**/*.xlsx'] });
  console.log('===>', tablePaths);
  //根据路径解析表格数据存入数组
  tablePaths.forEach((value, index) => {
    listDatas = listDatas.concat(xlsx.parse(sourcePath + '/' + value));
  });
  console.log('===>', listDatas);
  //名称重复检测
  repeatCheck(listDatas);
  //console.log('listDatas', listDatas)

  //创建文件夹
  fsExtra.removeSync(outPathTxt);
  fsExtra.removeSync(outPahtTs);
  fs.mkdirSync(outPathTxt);
  fs.mkdirSync(outPahtTs);

  //生成.txt和ts文件
  setFileToDirectory(listDatas);
}
else {
  console.log('缺少路径参数！')
}

